package inabit.inabitcompiler.productions.rule.expressions.arithmetic;

import inabit.compiler.parser.grammar.NonTerminal;
import inabit.compiler.parser.grammar.Production;
import inabit.compiler.parser.grammar.Symbol;
import inabit.data.expression.arithmetic.ArithmeticExpression;
import inabit.data.expression.arithmetic.ExponentiationExpression;
import inabit.inabitcompiler.parser.InabitSemanticAction;

/**F -> ZZ'*/
/**@author Rafael Rocha*/
public class F_Rule extends Production{
	private NonTerminal Z;
	private NonTerminal Z1;
	
	public F_Rule() {
		super("F");
	}
	
	public Symbol[] production(final NonTerminal nonTerminal) {
		Z = new NonTerminal("Z");
		Z1 = new NonTerminal("Z'");
		Symbol[] symbols = {
			Z,
			Z1,
			new InabitSemanticAction(nonTerminal) {
				public void execute() throws Exception {
					if(Z1.code.isEmpty()) {
						nonTerminal.code = Z.code;
					}else {
						ArithmeticExpression aExpr;
						String[] right = Z1.code.split(":");
						String op = right[0];
						if(op.equals("^")) {
							aExpr = new ExponentiationExpression(
								getArithmeticExpression(Z.code),
								getArithmeticExpression(right[1]));
						}else {
							throw new Exception("Cant recognize operator " + op + " in this context ");
						}
						nonTerminal.code = addArithmeticExpressionAndGetCode(aExpr);
					}
				}
			}
		};
		return symbols;
	}
}
